package projeto;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

import projeto.domain.NivelUsuarioEnum;
import projeto.domain.Usuario;

public class Database {
	
	private static String url = "jdbc:mysql://127.0.0.1";
	
	private static String user = "root";
	
	private static String password = "";
	
	private static String forName = "com.mysql.jdbc.Driver";

	public static String getUrl() {
		return url;
	}

	public static String getUser() {
		return user;
	}

	public static String getPassword() {
		return password;
	}
	
	public static void executeUpdate( final String query ) {
		
		try {
			
			Class.forName( forName ).newInstance();
			
			try {
				
				Connection conn = DriverManager.getConnection( url, user, password );
				
				Statement stm = conn.createStatement();
				
				stm.executeUpdate( query );
				
			} catch ( Exception e ) {
				
				e.printStackTrace();
			}
			
		} catch ( Exception e ) {
			
			e.printStackTrace();
		}
	}
	
	public static Usuario searchUsuario( final String query ) {
		
		Usuario result = new Usuario();
		
		try {
			
			Connection conn = DriverManager.getConnection( url, user, password );
			
			Statement stm = conn.createStatement();
			
			ResultSet rs = stm.executeQuery( query );
			
			while( rs.next() ) {
									
				result.setId( rs.getInt( "id" ) );
				result.setNome( rs.getString( "nome" ) );
				result.setNivel( NivelUsuarioEnum.getNivelUsuarioById( rs.getInt( "nivel" ) ) );
				result.setEmail( rs.getString( "email" ) );
				result.setTelefone( rs.getString( "telefone" ) );
				result.setSenha( rs.getString( "senha" ) );
			}
			
		} catch ( Exception e ) {
			
			e.printStackTrace();
		}
		
		return result;
	}
	
}
